package com.shark.security.jwt.security.rbac;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;

import com.shark.security.jwt.security.model.JwtUser;
import com.shark.security.jwt.security.model.MyGrantedAuthority;

/**
 * 返回权限验证的接口
 * 
 * @author junxiao
 *
 */
@Service("rbacService")
public class RbacService {

	private AntPathMatcher antPathMatcher = new AntPathMatcher();

	@SuppressWarnings("unchecked")
	public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
		Object principal = authentication.getPrincipal();
		boolean hasPermission = false;
		if (principal instanceof JwtUser) { // 首先判断先当前用户是否是我们UserDetails对象。
			Collection<MyGrantedAuthority> authorities = (Collection<MyGrantedAuthority>) ((JwtUser) principal)
					.getAuthorities();

			// 注意这里不能用equal来判断，因为有些URL是有参数的，所以要用AntPathMatcher来比较
			for (MyGrantedAuthority auth : authorities) {
				String method = auth.getMethod();
				if (antPathMatcher.match(auth.getUrl(), request.getRequestURI())) {
					//当权限表权限的method为ALL时表示拥有此路径的所有请求方式权利。
					if (method.equals(request.getMethod()) || "ALL".equals(method)) {
						hasPermission = true;
						break;
					}
				}
			}
		}
		return hasPermission;
	}
}
